import axios from 'axios'

const api = axios.create({
  baseURL: '/api'
})

export const fetchAIModels = async () => {
  const response = await api.get('/ai-models')
  return response.data
}

export const fetchAIModel = async (id) => {
  const response = await api.get(`/ai-models/${id}`)
  return response.data
}

export const createAIModel = async (data) => {
  const response = await api.post('/ai-models', data)
  return response.data
}

export const updateAIModel = async (id, data) => {
  const response = await api.put(`/ai-models/${id}`, data)
  return response.data
}

export const deleteAIModel = async (id) => {
  const response = await api.delete(`/ai-models/${id}`)
  return response.data
}

export const testAIModel = async (id, message) => {
  const response = await api.post(`/ai-models/${id}/test`, { message })
  return response.data
}

export async function streamTestAIModel(modelId, message, onChunk, onError, onComplete) {
  try {
    const response = await fetch(`/api/ai-models/${modelId}/stream`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        ...(localStorage.getItem('token') ? { 'Authorization': `Bearer ${localStorage.getItem('token')}` } : {})
      },
      body: JSON.stringify({ message })
    });

    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.detail || '流式测试失败');
    }

    // 处理 SSE 流
    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let buffer = '';

    while (true) {
      const { done, value } = await reader.read();
      
      if (done) {
        if (onComplete) onComplete();
        break;
      }
      
      // 解码并添加到缓冲区
      buffer += decoder.decode(value, { stream: true });
      
      // 处理缓冲区中的所有完整事件
      const lines = buffer.split('\n\n');
      buffer = lines.pop() || ''; // 保留最后一个不完整的事件
      
      for (const line of lines) {
        if (line.trim() === '') continue;
        if (line.trim() === 'data: [DONE]') {
          if (onComplete) onComplete();
          continue;
        }
        
        try {
          const dataMatch = line.match(/^data: (.+)$/);
          if (dataMatch) {
            const data = JSON.parse(dataMatch[1]);
            if (data.error) {
              if (onError) onError(new Error(data.error));
            } else if (data.content) {
              if (onChunk) onChunk(data.content);
            }
          }
        } catch (e) {
          console.error('解析 SSE 数据失败:', e, line);
        }
      }
    }
  } catch (error) {
    if (onError) onError(error);
    throw error;
  }
} 